package com.rainszj.controller.site;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rainszj.pojo.vo.IndexBlog;
import com.rainszj.service.BlogService;
import com.rainszj.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import static com.rainszj.constant.WebConstant.*;

/**
 * 前台分类页
 *
 * @author rainszj
 * 2020/3/17
 */
@Controller
public class CategoryController {

    @Autowired
    private TypeService typeservice;
    @Autowired
    private BlogService blogService;

    /**
     * 展示分类下的所有博客
     *
     * @param pageNum
     * @param model
     * @return
     */
    @GetMapping("/category.html")
    public String list(@RequestParam(defaultValue = "1") Integer pageNum,
                       Model model) {
        PageInfo<IndexBlog> pageInfo = PageHelper.startPage(pageNum, PAGE_SIZE).doSelectPageInfo(() -> blogService.listIndexBlog());
        model.addAttribute("types", typeservice.listAllType());
        model.addAttribute("pageInfo", pageInfo);
        // 给定一个常量，默认显示不激活
        model.addAttribute("activeTypeId", -1L);
        return "site/types";
    }


    /**
     * 查询指定分类的博客
     *
     * @return
     */
    @GetMapping("/category/{id}")
    public String queryTypeList(@RequestParam(defaultValue = "1", name = "pageNum") Integer pageNum,
                                @PathVariable("id") Long id,
                                Model model) {
        PageHelper.startPage(pageNum, PAGE_SIZE);
        // 根据分类id查询博客
        PageInfo<IndexBlog> pageInfo = new PageInfo<IndexBlog>(blogService.getIndexBlogByTypeId(id));
        // 与博客连接的分类
        model.addAttribute("types", typeservice.listAllType());
        model.addAttribute("pageInfo", pageInfo);
        // 要激活的分类的 Id
        model.addAttribute("activeTypeId", id);
        return "site/types";
    }


}
